package com.itfreer.gis.mapzone;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.itfreer.gis.OptionResult;
import com.itfreer.gis.OptionType;
import com.itfreer.gis.graphic.GisGraphic;
import com.itfreer.utils.json.JsonUtils;
/**
 * mapzone要素服务处理功能
 * @author gj
 *
 */
public class MapzoneOption {
	/**
	 * 添加要素功能
	 * @param baseUrl feature服务地地址如（http://192.168.1.120:6080/arcgis/rest/services/TEST/FeatureServer）
	 * @param layerId 图层id(如 0)
	 * @param graphic 图形
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public OptionResult addFeature(String baseUrl,GisGraphic graphic,
			String DataSpaceName,String TableName){
		OptionResult option=new OptionResult();
		option.setGraphic(graphic);
		option.setOptionType(OptionType.add);
		
		try {
			int FeatureCount =0;
			if(graphic.getAttribute()!=null && graphic.getAttribute().get(graphic.getKeyField())!=null) {
				Integer intGuid=(Integer)graphic.getAttribute().get(graphic.getKeyField());
				FeatureCount =this.queryFeature(baseUrl,intGuid,null, DataSpaceName, TableName);
			}
			
			if(FeatureCount<1) {
				
				// 创建HTTP客户端
				CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(MapzoneConstants.REQUEST_CONFIG).build();
				// 查询当前新增的box在ArcGis中是否存在
				// 创建POST请求
				HttpPost httpPost = new HttpPost(baseUrl);
				// 运行到这里说明该box在ArcGis中不存在, 执行新增操作
				// 创建POST请求参数, 必须用NameValuePair
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("OPERATION", MapzoneConstants.ADD_FEATURE));
				params.add(new BasicNameValuePair("VERSION", "1.0.0"));
				params.add(new BasicNameValuePair("DataSpaceName", DataSpaceName));
				params.add(new BasicNameValuePair("TableName", TableName));
				//params.add(new BasicNameValuePair("PK_UID", layerId.toString()));//mapzone 记录主键
				params.add(new BasicNameValuePair("Geometry", graphic.getGeometry()));//wkt格式
				//params.add(new BasicNameValuePair("XMBH", fileName));//业务代码
				params.add(new BasicNameValuePair("username", "admin"));
				params.add(new BasicNameValuePair("password", "123"));
				if(graphic.getAttribute()!=null && graphic.getAttribute().size()>0) {
					Set<String> keys=graphic.getAttribute().keySet();
					for(String key:keys) {
						params.add(new BasicNameValuePair(key, graphic.getAttribute().get(key).toString()));
					}
				}
				// 设置POST请求参数,并将参数格式设置为utf-8
				HttpEntity entity = new UrlEncodedFormEntity(params, MapzoneConstants.DEFAULT_CHARSET);
				httpPost.setEntity(entity);
				
				// 发送请求
				HttpResponse response = httpclient.execute(httpPost);
				
				// 处理结果集
				if (response.getStatusLine().getStatusCode() == 200) {
				  // 调用EntityUtils.toString方法最后会自动把inputStream close掉的
				  String str = EntityUtils.toString(response.getEntity());
				  // 将xml格式字符串转化为DOM对象
		          Document document = DocumentHelper.parseText(str);
		          // 获取根结点对象
		          Element rootElement = document.getRootElement();
		          //循环子节点
		          String ResultValue=null;
		          for (Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
		        	  Element element = (Element) iter.next();
		        	  String name=element.getName();
		        	  if("ResultValue".equals(name)){
		        		  ResultValue=element.getTextTrim();
		        	  }
		          }
		          if("True".equals(ResultValue)){
					  option.setStatus(true);
					  option.setMessager("导入成功");
		          }else{
		        	  option.setStatus(false);
					  option.setMessager("导入失败");
		          }
				  // 释放资源
				  httpclient.close();
				} else {
					option.setStatus(false);
					option.setMessager("网络请求失败");
				}
			}else {
				return this.updateFeature(baseUrl, graphic, DataSpaceName, TableName);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
			option.setStatus(false);
			option.setMessager("网络请求失败");
		} 
	    return option;
	}

	/**
	 * arcgis要素查询服务
	 * @param baseUrl http://192.168.1.120:6080/arcgis/rest/services/TEST/FeatureServer
	 * @param layerId 0
	 * @param where sheng=44
	 * @param objectIds 8808,8805
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unused", "rawtypes" })
	public int queryFeature(String baseUrl,Integer intGuid,String where,String DataSpaceName,String TableName) throws Exception {
		int FeatureCount=0;
		// 创建HTTP客户端
	    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(MapzoneConstants.REQUEST_CONFIG).build();
	    // 创建POST请求
		HttpPost httpPost = new HttpPost(baseUrl);
		// 创建POST请求参数, 必须用NameValuePair
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("OPERATION", MapzoneConstants.SELECT_FEATURES));
		params.add(new BasicNameValuePair("VERSION", "1.0.0"));
		params.add(new BasicNameValuePair("DataSpaceName", DataSpaceName));
		params.add(new BasicNameValuePair("TableName",  TableName));
		params.add(new BasicNameValuePair("Filter", "PK_UID="+intGuid));
		params.add(new BasicNameValuePair("username", "admin"));
		params.add(new BasicNameValuePair("password", "123"));
	    //设置http Post请求参数
	    HttpEntity entity = new UrlEncodedFormEntity(params, MapzoneConstants.DEFAULT_CHARSET);
	    httpPost.setEntity(entity);
	    // 发送请求
	    HttpResponse response = httpclient.execute(httpPost);
	    // 处理结果集
	    Map<String, Object> oldFeature = new HashMap<String, Object>();
	    if (response.getStatusLine().getStatusCode() == 200) {
	       // 调用EntityUtils.toString方法最后会自动把inputStream close掉的
	       String result = EntityUtils.toString(response.getEntity());
	       //result为xml格式
	       // 将xml格式字符串转化为DOM对象
           Document document = DocumentHelper.parseText(result);
           // 获取根结点对象
           Element rootElement = document.getRootElement();
           //获取子节点
           Iterator iters = rootElement.elementIterator(); 
           Element elements = (Element) iters.next();
           //循环子节点下的子节点
           for (Iterator iter = elements.elementIterator(); iter.hasNext();) {
        	   Element element = (Element) iter.next();
        	   String name=element.getName();
        	   if("FeatureCount".equals(name)){
        		   FeatureCount=Integer.parseInt(element.getTextTrim());
        	   }
           }
	    }
	    // 释放资源
	    httpclient.close();
	    return FeatureCount;
	}
	
	/**
	 * 更新要素服务
	 * @param baseUrl
	 * @param layerId
	 * @param graphic
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public OptionResult updateFeature(String baseUrl,GisGraphic graphic,String DataSpaceName,String TableName){
		graphic.setKeyField("PK_UID");
		OptionResult option=new OptionResult();
		option.setGraphic(graphic);
		option.setOptionType(OptionType.update);
		try {
			// 创建HTTP客户端
			CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(MapzoneConstants.REQUEST_CONFIG).build();
			// 查询当前被修改的box在ArcGis中是否存在
			
			int FeatureCount =0;
			if(graphic.getAttribute()!=null && graphic.getAttribute().get(graphic.getKeyField())!=null) {
				Integer intGuid=(Integer)graphic.getAttribute().get(graphic.getKeyField());
				FeatureCount =this.queryFeature(baseUrl,intGuid,null, DataSpaceName, TableName);
			}
			if (FeatureCount > 0) {
				// 创建POST请求
				HttpPost httpPost = new HttpPost(baseUrl);
				// 创建POST请求参数, 必须用NameValuePair
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("OPERATION", MapzoneConstants.UPDATE_FEATURE));
				params.add(new BasicNameValuePair("VERSION", "1.0.0"));
				params.add(new BasicNameValuePair("DataSpaceName", DataSpaceName));
				params.add(new BasicNameValuePair("TableName", TableName));
				//params.add(new BasicNameValuePair("PK_UID", intGuid.toString()));//mapzone中的主键
				params.add(new BasicNameValuePair("Geometry", graphic.getGeometry()));
				params.add(new BasicNameValuePair("username", "admin"));
				params.add(new BasicNameValuePair("password", "123"));
				if(graphic.getAttribute()!=null && graphic.getAttribute().size()>0) {
					Set<String> keys=graphic.getAttribute().keySet();
					for(String key:keys) {
						params.add(new BasicNameValuePair(key, graphic.getAttribute().get(key).toString()));
					}
				}
			    // 设置POST请求参数,并将参数格式设置为utf-8
			    HttpEntity entity = new UrlEncodedFormEntity(params, MapzoneConstants.DEFAULT_CHARSET);
			    httpPost.setEntity(entity);
			    // 发送请求
			    HttpResponse response = httpclient.execute(httpPost);
			    // 处理结果集
			    if (response.getStatusLine().getStatusCode() == 200) {
			          // 调用EntityUtils.toString方法最后会自动把inputStream close掉的
			          String str=EntityUtils.toString(response.getEntity());
			          // 将xml格式字符串转化为DOM对象
			          Document document = DocumentHelper.parseText(str);
			          // 获取根结点对象
			          Element rootElement = document.getRootElement();
			          //循环子节点
			          String ResultValue=null;
			          for (Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
			        	  Element element = (Element) iter.next();
			        	  String name=element.getName();
			        	  if("ResultValue".equals(name)){
			        		  ResultValue=element.getTextTrim();
			        	  }
			          }
			          if("True".equals(ResultValue)){
						  option.setStatus(true);
						  option.setMessager("更新成功");
			          }else{
			        	  option.setStatus(false);
						  option.setMessager("更新失败");
			          }
			          // 释放资源
			          httpclient.close();
		        } else {
		        	option.setStatus(false);
		        	option.setMessager("请求未得到响应");
		        }
		    }else {
		    	return this.addFeature(baseUrl, graphic,DataSpaceName, TableName);
		    }
			return option;
		} catch (Exception e) {
			return option;
		}
	} 
}
